#/usr/bin/python
# -*- coding: utf-8 -*-

import csv
import parameters


class Parser(object):
    
    def __init__(self, domain, filename, paramfile=None):
        
        self.domain = domain
        self.filename = filename
        self.paramFile = paramfile
        
    def writeOutputFile(self):
        '''
            write the saved quantities of interest into a file whose format is defined as parameter.
            Quantities of interest are saved as Quantity objects associated to a mesh. The Quantity objects are associating state identifiers
            with data. The mapping of states (type "STEP" or "MODE", ordering) is hold by the domain object. 
            
            
        
        '''
        return 0
    
    
    

class ParserCSV(Parser):
    '''
        Class of output parser for .csv files. 
    '''
    
    DELIMITER = ','
    DECIMALDOT = '.'
    
    def writeOutputFile(self):
        '''
            Based on csv.writer() object and its writerow(row, ) method.
        '''
        # init param and writer:
        param = parameters.load()

        # for each domain:
        try:
            for domain in self.domain.domains: # this is a global domain
                parser = ParserCSV(domain, self.filename + domain.UId)
                parser.writeOutputFile()
        except:
            pass # non global domain
        
        # states by type:
        for type in self.domain.qoiMap.keys():
            
            statekeys = self.domain.qoiMap[type]
            if not len(statekeys): continue
            
            
            args = {}
            for m in self.domain.meshes:
                # header:
                csvfile = open(param.WORKDIR + self.filename + '-mesh-' + str(m.UId) + '.csv', 'wb')
                writer = csv.writer(csvfile, delimiter=self.DELIMITER)
                row = ['states']
                row.extend(statekeys)
                writer.writerow(row)
                if type=='STEP':
                    row = ['iter']
                elif type=='MODE':
                    row = ['mode']
                else:
                    row = ['stateid']
                row.extend(range(len(statekeys)))
                writer.writerow(row)
                m.quantities.unPickle()
                print m.quantities.quantities.keys()
                
                for qoi in m.quantities.quantities.values():
                    if not qoi.active:
                        args[qoi.name] = param.getOutputQOI(qoirequest=qoi.name)
                        continue
                    
                for qoi in m.quantities.quantities.values():
                    if not qoi.active: continue
                    
                    qargs = None
                    for q in args.keys():
                        if q in qoi.name:
                            qargs = args[q]
                            break

                    if qargs: # split per components:
                        dofs = [eval(i) for i in qargs[1]]
                        for i,d in enumerate(dofs):
                            row = [qoi.name+'-'+str(d)]
                            row.extend([qoi.states[m.quantities.statesMap[st]][i] for st in statekeys])
                            writer.writerow(row)
                    else:
                        row = [qoi.name]
                        row.extend([qoi.states[m.quantities.statesMap[st]] for st in statekeys])
#                        print 'row:', row
                        writer.writerow(row)
            
                csvfile.close()
#        self.paramfile = 